import matplotlib.pyplot as plt
import numpy as np


def function(x):
    return 0.01 * x ** 2 + 0.1 * x


def numercical_diff(f, x):
    h = 1e-4
    y = (f(x + h) - f(x - h)) / (2 * h)
    return y


def tangent_function(f, x):
    d = numercical_diff(f, x)
    print('近似切线的斜率是： ' + str(d))
    b = f(x) - d * x  # 近似切线截距

    return lambda t: d * t + b


def true_tangent_function(f, x):
    d = 0.2
    b = f(x) - d * x
    return lambda t: d * t + b


if __name__ == '__main__':
    x = np.arange(0, 20, 0.1)
    y = function(x)

    # 具体某一点的近似切线
    tf = tangent_function(function, 5)
    y1 = tf(x)

    tff = true_tangent_function(function, 5)
    y2 = tff(x)

    plt.ylim(-0.5, 6)
    plt.title("Research the funciton's feature")
    plt.xlabel('x')
    plt.ylabel('y')

    plt.plot(x, y, label='source_function')
    plt.plot(x, y1, label='appro_tangent_line')
    plt.plot(x, y2, label='true_tangent_line', linestyle='--')

    plt.legend()
    plt.show()
